export default class NetworkManager {
  constructor() {
    this.socket = null
    this.roomId = null
    this.playerId = null
    this.isHost = false
    this.connected = false
    this.gameStarted = false
    this.opponentConnected = false
    
    // 检测运行环境
    this.isWeChat = typeof wx !== 'undefined' && wx.connectSocket
    
    // 回调函数
    this.onGameStart = null
    this.onMoveReceived = null
    this.onOpponentConnected = null
    this.onOpponentDisconnected = null
    this.onGameOver = null
  }

  // 连接到服务器
  connect(serverUrl = 'wss://your-websocket-server.com') {
    return new Promise((resolve, reject) => {
      try {
        if (this.isWeChat) {
          // 微信小程序环境
          this.socket = wx.connectSocket({
            url: serverUrl,
            success: () => {
              console.log('微信WebSocket连接成功')
              this.connected = true
              resolve()
            },
            fail: (error) => {
              console.error('微信WebSocket连接失败:', error)
              this.connected = false
              reject(error)
            }
          })
          
          // 监听连接打开
          wx.onSocketOpen(() => {
            console.log('微信WebSocket连接已打开')
            this.connected = true
            resolve()
          })
          
          // 监听消息
          wx.onSocketMessage((res) => {
            try {
              const data = JSON.parse(res.data)
              this.handleMessage(data)
            } catch (error) {
              console.error('解析消息失败:', error)
            }
          })
          
          // 监听连接关闭
          wx.onSocketClose(() => {
            console.log('微信WebSocket连接关闭')
            this.connected = false
            this.opponentConnected = false
            if (this.onOpponentDisconnected) {
              this.onOpponentDisconnected()
            }
          })
          
          // 监听连接错误
          wx.onSocketError((error) => {
            console.error('微信WebSocket错误:', error)
            this.connected = false
            reject(error)
          })
        } else {
          // 浏览器环境
          this.socket = new WebSocket(serverUrl)
          
          this.socket.onopen = () => {
            console.log('WebSocket连接成功')
            this.connected = true
            resolve()
          }
          
          this.socket.onmessage = (event) => {
            this.handleMessage(JSON.parse(event.data))
          }
          
          this.socket.onclose = () => {
            console.log('WebSocket连接关闭')
            this.connected = false
            this.opponentConnected = false
            if (this.onOpponentDisconnected) {
              this.onOpponentDisconnected()
            }
          }
          
          this.socket.onerror = (error) => {
            console.error('WebSocket错误:', error)
            this.connected = false
            reject(error)
          }
        }
      } catch (error) {
        console.error('创建WebSocket失败:', error)
        reject(error)
      }
    })
  }

  // 创建房间
  createRoom() {
    if (!this.connected) {
      throw new Error('WebSocket未连接')
    }
    
    this.isHost = true
    this.roomId = this.generateRoomId()
    this.playerId = 'player1'
    
    this.sendMessage({
      type: 'create_room',
      roomId: this.roomId,
      playerId: this.playerId
    })
    
    return this.roomId
  }

  // 加入房间
  joinRoom(roomId) {
    if (!this.connected) {
      throw new Error('WebSocket未连接')
    }
    
    this.isHost = false
    this.roomId = roomId
    this.playerId = 'player2'
    
    this.sendMessage({
      type: 'join_room',
      roomId: this.roomId,
      playerId: this.playerId
    })
  }

  // 发送落子信息
  sendMove(row, col, player) {
    if (!this.connected || !this.roomId) {
      throw new Error('未连接到房间')
    }
    
    this.sendMessage({
      type: 'move',
      roomId: this.roomId,
      playerId: this.playerId,
      row: row,
      col: col,
      player: player
    })
  }

  // 发送游戏结束信息
  sendGameOver(winner) {
    if (!this.connected || !this.roomId) {
      return
    }
    
    this.sendMessage({
      type: 'game_over',
      roomId: this.roomId,
      playerId: this.playerId,
      winner: winner
    })
  }

  // 发送结束游戏信息
  sendSurrender() {
    if (!this.connected || !this.roomId) {
      return
    }
    
    this.sendMessage({
      type: 'surrender',
      roomId: this.roomId,
      playerId: this.playerId
    })
  }

  // 处理接收到的消息
  handleMessage(data) {
    console.log('收到消息:', data)
    
    switch (data.type) {
      case 'room_created':
        console.log('房间创建成功:', data.roomId)
        break
        
      case 'room_joined':
        console.log('成功加入房间')
        this.opponentConnected = true
        if (this.onOpponentConnected) {
          this.onOpponentConnected()
        }
        break
        
      case 'player_joined':
        console.log('对手加入房间')
        this.opponentConnected = true
        if (this.onOpponentConnected) {
          this.onOpponentConnected()
        }
        break
        
      case 'game_start':
        console.log('游戏开始')
        this.gameStarted = true
        if (this.onGameStart) {
          this.onGameStart()
        }
        break
        
      case 'move':
        console.log('收到对手落子:', data)
        if (this.onMoveReceived) {
          this.onMoveReceived(data.row, data.col, data.player)
        }
        break
        
      case 'game_over':
        console.log('游戏结束:', data.winner)
        if (this.onGameOver) {
          this.onGameOver(data.winner)
        }
        break
        
      case 'surrender':
        console.log('对手结束游戏')
        if (this.onGameOver) {
          // 对手结束游戏，当前玩家获胜
          const myStoneColor = this.getMyStoneColor()
          this.onGameOver(myStoneColor)
        }
        break
        
      case 'error':
        console.error('服务器错误:', data.message)
        break
        
      default:
        console.log('未知消息类型:', data.type)
    }
  }

  // 发送消息
  sendMessage(message) {
    if (this.isWeChat) {
      // 微信小程序环境
      if (this.connected) {
        wx.sendSocketMessage({
          data: JSON.stringify(message),
          success: () => {
            console.log('消息发送成功')
          },
          fail: (error) => {
            console.error('消息发送失败:', error)
          }
        })
      } else {
        console.error('微信WebSocket未连接')
      }
    } else {
      // 浏览器环境
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(JSON.stringify(message))
      } else {
        console.error('WebSocket未连接')
      }
    }
  }

  // 生成房间ID
  generateRoomId() {
    return Math.random().toString(36).substring(2, 8).toUpperCase()
  }

  // 断开连接
  disconnect() {
    if (this.isWeChat) {
      // 微信小程序环境
      if (this.connected) {
        wx.closeSocket({
          success: () => {
            console.log('微信WebSocket连接已关闭')
          },
          fail: (error) => {
            console.error('关闭微信WebSocket失败:', error)
          }
        })
      }
    } else {
      // 浏览器环境
      if (this.socket) {
        this.socket.close()
      }
    }
    
    this.connected = false
    this.opponentConnected = false
    this.gameStarted = false
    this.roomId = null
    this.playerId = null
    this.isHost = false
  }

  // 获取房间链接
  getRoomLink() {
    if (!this.roomId) return null
    
    if (this.isWeChat) {
      // 微信小程序环境，返回房间ID
      return this.roomId
    } else {
      // 浏览器环境
      if (typeof window !== 'undefined' && window.location) {
        return `${window.location.origin}${window.location.pathname}?room=${this.roomId}`
      } else {
        // 兼容其他环境
        return `room:${this.roomId}`
      }
    }
  }

  // 检查是否是我的回合
  isMyTurn(currentPlayer) {
    if (this.isHost) {
      return currentPlayer === 1 // 房主执黑先手
    } else {
      return currentPlayer === 2 // 加入者执白后手
    }
  }

  // 获取我的棋子颜色
  getMyStoneColor() {
    return this.isHost ? 1 : 2 // 1=黑棋, 2=白棋
  }
} 